<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">名称</label>
        <el-input
          v-model="query.name"
          clearable
          placeholder="名称"
          style="width: 185px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">类型</label>
        <el-select
          v-model="query.category"
          clearable
          style="width: 185px"
          placeholder="类型"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.label"
            :label="item.value"
            :value="item.label"
          />
        </el-select>
        <label class="el-form-item-label">入库时间</label>
        <date-range-picker v-model="query.createdAt" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="550px"
      >
        <el-form
          class="form"
          ref="form"
          :model="form"
          :rules="rules"
          size="small"
          label-width="90px"
        >
          <el-form-item label="名称" prop="name">
            <el-select
              v-model="form.name"
              style="width: 370px"
              clearable
              filterable
              allow-create
              reserve-keyword
              :remote-method="getName"
              placeholder="请添加名称"
              @visible-change="nameVisible"
              ref="nameSel"
            >
              <el-option
                v-for="item in names"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="危化品类型" prop="type">
            <el-input v-model="form.type" style="width: 370px;" />
          </el-form-item> -->
          <el-form-item label="类型" prop="category">
            <el-select
              v-model="form.category"
              style="width: 370px"
              placeholder="请选择类型"
              @blur="selectBlur"
              filterable
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.category == 1" label="规格" prop="capacity">
            <el-input
              type="number"
              v-model="form.capacity"
              style="width: 350px"
            />ml
          </el-form-item>
          <div style="display: flex">
            <el-form-item label="数量" prop="amount">
              <el-input
                min="0"
                type="number"
                v-model="form.amount"
                style="width: 170px"
                placeholder="请填入数量"
              />
            </el-form-item>
            <el-form-item class="unit" prop="unit">
              <el-select
                v-model.number="form.unit"
                style="width: 170px"
                placeholder="请选择单位"
                filterable
                clearable
              >
                <el-option
                  v-for="item in unitOptions"
                  :key="item.label"
                  :label="item.value"
                  :value="item.label"
                />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="仓库" prop="storage">
            <el-select
              v-model="form.storage"
              style="width: 370px"
              placeholder="请选择仓库"
            >
              <el-option
                v-for="item in storageOptions"
                :key="item.label"
                :label="item.value"
                :value="item.label"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="是否申领" prop="isApply">
            <el-radio-group v-model="form.isApply" @input="changeIsApply">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item
            label="是否审批"
            prop="isAudit"
          >
            <el-radio-group v-model="form.isAudit">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="位置">
            <el-input v-model="form.location" style="width: 370px" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="form.note"
              :rows="3"
              type="textarea"
              style="width: 370px"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu === 2"
            type="primary"
            @click="crud.submitCU"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column label="条码" prop="barCode" align="center">
          <template slot-scope="scope">
           <div class="barCode">
            <el-image
              :src="
                baseUrl +
                '/api/barCode/showBarCode?id=' +
                scope.row.id +
                '&type=' +
                scope.row.type
              "
              style="height: 40px; vertical-align: middle"
              :preview-src-list="srcList"
              @click="enlargeBarcode(scope.row)"
            />
            <span>{{ scope.row.id }}</span>
           </div>
          </template>
        </el-table-column>
        <el-table-column label="二维码" prop="QRCode" align="center">
          <template slot-scope="scope">
            <el-image
              :src="
                baseUrl +
                '/api/barCode/showQRCode?id=' +
                scope.row.id +
                '&type=' +
                scope.row.type
              "
              style="height: 40px; vertical-align: middle"
              :preview-src-list="srcList"
              @click="enlargeQRCode(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="category" label="类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.category == 1">玻璃器皿</span>
            <span v-else-if="scope.row.category == 2">实验耗材</span>
            <span v-else-if="scope.row.category == 3">采样工具</span>
            <span v-else-if="scope.row.category == 4">仪器设备</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="数量" align="center" />
        <el-table-column prop="residue" label="剩余量" align="center" />
        <el-table-column prop="unit" label="单位" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.unit == 1">个</span>
            <span v-else-if="scope.row.unit == 2">台</span>
            <span v-else-if="scope.row.unit == 3">套</span>
          </template>
        </el-table-column>
        <el-table-column prop="storage" label="仓库" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.storage == 1">器材室</span>
            <span v-else-if="scope.row.storage == 2">备品室</span>
            <span v-else-if="scope.row.storage == 3">外业仓库</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="入库时间" align="center" width="135"/>
        <el-table-column prop="location" label="位置" align="center" />
        <el-table-column prop="note" label="备注" align="center" />
        <el-table-column label="条形码" align="center">
          <template slot-scope="scope">
            <button
              class="el-button el-button--primary el-button--mini"
              @click="barView(scope.row)"
            >
              <i class="el-icon-printer" size="100" />
            </button>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center">
          <template slot-scope="scope">
            <button
              class="el-button el-button--primary el-button--mini"
              @click="qrView(scope.row)"
            >
              <i class="el-icon-printer" size="100" />
            </button>
          </template>
        </el-table-column>
        <el-table-column
          v-if="
            checkPer([
              'admin',
              'hazardousChemicals:edit',
              'hazardousChemicals:del',
            ])
          "
          label="操作"
          width="180px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              class="isForbiddenBtn"
              @click="showAddNumDialog(scope.row)"
              >入库</el-button
            >
            <el-button
              type="success"
              class="isForbiddenBtn"
              @click="crud.toQuote(scope.row)"
              >引用</el-button
            >
            <udOperation
              :data="scope.row"
              :permission="permission"
              disabledEdit
            />
            <!-- disabledEdit 修改禁用 -->
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination ref="pag" />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="view"
      title="打印预览"
      width="350px"
    >
      <el-image
        :src="
          baseUrl +
          '/api/barCode/showBarCode?id=' +
          codeId +
          '&type=' +
          codeType
        "
      />
      <el-button
        type="primary"
        @click="fileDownload()"
        style="margin-left: 40%"
      >
        打印
      </el-button>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="views"
      title="打印预览"
      width="350px"
    >
      <el-image
        :src="
          baseUrl + '/api/barCode/showQRCode?id=' + codeId + '&type=' + codeType
        "
      />
      <el-button
        type="primary"
        @click="fileDownloadQR()"
        style="margin-left: 40%"
      >
        打印
      </el-button>
    </el-dialog>
    <AddNumDialog v-if="isShowAddNumDialog" @refresh="crud.pageChangeHandler(0)" @close="isShowAddNumDialog = false"  :isShowAddNumDialog="isShowAddNumDialog" :info="currentAddNumDialogInfo"/>
  </div>
</template>

<script>
import AddNumDialog from "./components/addNumConsumableDialog.vue";
import crudHazardousChemicals from "@/api/hazardousChemicals";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operationDelete";
import pagination from "@crud/Pagination";
import { get } from "@/api/lab";
import { getCabinet } from "@/api/cabinet";
import { showBarCode, print } from "@/api/barCode";
import DateRangePicker from "@/components/DateRangePicker";
import { printCode } from "@/api/barCode";
import {searchName} from "@/api/hazardousChemicals";
import { getStoreHouseAPI } from "@/api/hazardousChemicals.js";

const defaultForm = {
  id: null,
  name: null,
  type: 1,
  amount: null,
  capacity: null,
  labId: 1,
  note: null,
  createdAt: null,
  isDeleted: null,
  countType: 1,
  updatedAt: null,
  barCode: null,
  cabinetId: 13,
  measureId: 1,
  dangerClasses: 1,
  category: "",
  storage: null,
  location: null,
  unit: null,
  isApply: 1,
  isAudit: 0,
};
export default {
  name: "Consumable",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker,
    AddNumDialog
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: "器材",
      url: "api/hazardousChemicals",
      idField: "id",
      sort: "id,desc",
      crudMethod: { ...crudHazardousChemicals },
      query: {
        type: 1,
      },
      optShow: {
        add: true,
        edit: false,
        del: true,
        download: true,
        reset: true,
        printConsumable: true,
        printQRConsumable: true,
        equipmentUpload:true,
        equipmentBatchImport:true
      },
    });
  },
  data() {
    const limtCapacity = (rule, value, callback) => {
      if (this.form.category === 1 && !value) {
        return callback(new Error("请输入规格"));
      }
      callback();
    };
    let limtName =  (rule, value, callback) => {
      if (!value) {
        return callback(new Error("名称不能为空"));
      }
      //else if (this.names.some(item=>item.name==this.form.name)) {
      //  return callback(new Error("该名称器材已入库，请勿重复入库"));
      //}
      callback();
    };
    return {
      currentAddNumDialogInfo:{},
      isShowAddNumDialog:false,
      permission: {
        add: ["admin", "hazardousChemicals:add"],
        edit: ["admin", "hazardousChemicals:edit"],
        del: ["admin", "hazardousChemicals:del"],
      },
      rules: {
        name: [{required: true,trigger: "change",validator: limtName },
        {trigger: "blur",validator: limtName }],
        capacity: [
          { required: true, trigger: "blur", validator: limtCapacity },
        ],
        labId: [
          { required: true, message: "实验室不能为空", trigger: "change" },
        ],
        countType: [
          { required: true, message: "计数类型不能为空", trigger: "blur" },
        ],
        cabinetId: [
          { required: true, message: "试剂柜不能为空", trigger: "change" },
        ],
        storage: [{ required: true, message: "请选择仓库", trigger: "blur" }],
        unit: [{ required: true, message: "请选择单位", trigger: "blur" }],
        amount: [{ required: true, message: "请输入数量", trigger: "blur" }],
        category: [{ required: true, message: "请选择类型", trigger: "blur" }],
        dangerClasses: [
          { required: true, message: "危险等级不能为空", trigger: "blur" },
        ],
        // isApply: [
        //   { required: true, message: "请选择是否需要申领", trigger: "blur" },
        // ],
        isAudit: [
          { required: true, message: "请选择是否需要申领", trigger: "blur" },
        ],
      },
      queryTypeOptions: [
        { key: "name", display_name: "名称" },
        // { key: 'type', display_name: '危化品类型' },
        { key: "labName", display_name: "实验室" },
        { key: "countType", display_name: "计数类型" },
        { key: "cabinetName", display_name: "试剂柜" },
        // { key: 'measureId', display_name: '计量方式' },
        { key: "dangerClasses", display_name: "危险等级" },
      ],
      searchLoading: false,
      labs: [],
      names:[],
      cabinets: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      searchForm: {
        page: 1,
        size: 10,
        name: "",
        id: "",
      },
      srcList: [], //预览图片列表
      categoryOptions: [
        {
          value: "玻璃器皿",
          label: 1,
        },
        {
          value: "实验耗材",
          label: 2,
        },
        {
          value: "采样工具",
          label: 3,
        },
        {
          value: "仪器设备",
          label: 4,
        },
      ],
      storageOptions: [
        {
          value: "器材室",
          label: 1,
        },
        {
          value: "备品室",
          label: 2,
        },
        {
          value: "外业仓库",
          label: 3,
        },
      ],
      unitOptions: [
        {
          value: "个",
          label: 1,
        },
        {
          value: "台",
          label: 2,
        },
        {
          value: "套",
          label: 3,
        },
      ],
      view: false,
      views: false,
      codeId: "",
      codeType: "",
    };
  },
  created() {
    this.getLabs();
    this.getCabinets();
    this.getName();
    // this.showBarCode()
  },
  methods: {
    showAddNumDialog(row){
      this.currentAddNumDialogInfo = row
      this.isShowAddNumDialog= true
    },
    // unitBlur(){
    //   this.form.unit = this.$refs.unitSel.selectedLabel
    // },
    selectBlur(e) {
      //   this.form.category = e.target.value;
      //   this.$forceUpdate(); // 强制更新
    },
    getName() {
      searchName(1)
        .then((response) => {
          this.names = response;
        })
        .catch((_) => {
          console.log(response);
        });
    },
    // nameblur(){
    //   this.form.name = this.$refs.nameSel.selectedLabel
    // },
    nameVisible(e){
      if(e){
        this.$refs.nameSel.$data.selectedLabel = this.form.name
      }
    },
    getLabs() {
      get()
        .then((response) => {
          this.labs = response;
        })
        .catch((_) => {
          console.log(response);
        });
    },
    getCabinets(query = "") {
      this.searchForm.name = query;
      this.searchLoading = true;
      getCabinet(this.searchForm)
        .then((response) => {
          this.searchLoading = false;
          this.cabinets = response.content;
        })
        .catch((_) => {
          this.searchLoading = false;
        });
    },
    onChanged(value) {
      this.searchForm.name = "";
      this.searchLoading = true;
      getCabinet(this.searchForm)
        .then((response) => {
          this.searchLoading = false;
          this.cabinets = response.content;
          this.cabinets = this.cabinets.filter((item) => {
            return item.labId == value;
          });
          if (this.cabinets.length != 0) {
            this.form.cabinetId = this.cabinets[0].id;
          } else {
            this.form.cabinetId = null;
          }
        })
        .catch((_) => {
          this.searchLoading = false;
        });
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      // this.$store.dispatch("hjuser/getStoreHouse");
      return true;
    },
    [CRUD.HOOK.afterRefresh]() {
      this.crud.data = this.crud.data.map(
        (item) =>
          (item = {
            ...item,
            unit: Number(item.unit),
            category: Number(item.category),
          })
      );
      return true;
    },
    [CRUD.HOOK.afterDelete]() {
      // this.$store.dispatch("hjuser/getStoreHouse");
    },
    showBarCode() {
      showBarCode();
    },
    barView(row) {
      this.view = true;
      this.codeId = row.id;
      this.codeType = row.type;
    },
    qrView(row) {
      this.views = true;
      this.codeId = row.id;
      this.codeType = row.type;
    },
    fileDownload(row) {
      printCode({
        itemId: this.codeId,
        itemType: 1,
        codeType: 1,
      }).then((res) => {
        this.$message.success("已添加到打印队列");
      });
    },
    fileDownloadQR(row) {
      printCode({
        itemId: this.codeId,
        itemType: 1,
        codeType: 2,
      }).then((res) => {
        this.$message.success("已添加到打印队列");
      });
    },
    enlargeBarcode(row) {
      var arr =
        this.baseUrl +
        "/api/barCode/showBarCode?id=" +
        row.id +
        "&type=" +
        row.type;
      this.srcList = arr.split(";");
    },
    enlargeQRCode(row) {
      var arr =
        this.baseUrl +
        "/api/barCode/showQRCode?id=" +
        row.id +
        "&type=" +
        row.type;
      this.srcList = arr.split(";");
    },
    async [CRUD.HOOK.afterSubmit](val) {
      this.isApply = 1;
      this.isAudit = 0;
      this.getName();
    },
    changeIsApply(val) {
      if (val == 0) {
        this.form.isAudit = 0;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.el-form::v-deep {
  div.unit {
    .el-form-item__content {
      margin-left: 30px !important;
    }
  }
}
.el-table ::v-deep .cell {
  display: flex;
  align-items: center;
  justify-content: center;

  .isForbiddenBtn {
    width: 43px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    margin-right: 5px;
    padding: 0;
  }
  .barCode {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
